import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_exam.dart';
import 'package:flutter_learn_vi/src/bean/bean_exam_result.dart';
import 'package:flutter_learn_vi/src/bean/bean_problem_end.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_details_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_enum.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import '../../bean/bean_ExamBean.dart';
import '../../bean/bean_train_exam_appro.dart';
import '../../utils/log_util.dart';
import 'model/train_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/2/17.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class TrainExamPage extends StatefulWidget {
  final TrainApproveBean approveBean;
  final List<BeanExamResult> examResultList;

  const TrainExamPage({
    Key key,
    this.approveBean,
    this.examResultList,
  }) : super(key: key);

  @override
  _TrainExamPageState createState() => _TrainExamPageState();
}

class _TrainExamPageState extends State<TrainExamPage> with TrainModel {
  List<BeanExamResult> _examResultList;

  @override
  void initState() {
    super.initState();
    _examResultList = widget.examResultList;
    _getExamDetails();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("培训考试"),
      ),
      backgroundColor: Colors.white,
      body: Container(
          width: double.infinity,
          height: double.infinity,
          padding: EdgeInsets.all(12),
          child: Stack(
            children: [
              Positioned(
                child: RefreshIndicator(
                  notificationPredicate: (ScrollNotification notifation) {
                    //该属性包含当前ViewPort及滚动位置等信息
                    ScrollMetrics scrollMetrics = notifation.metrics;
                    if (scrollMetrics.minScrollExtent == 0) {
                      return true;
                    } else {
                      return false;
                    }
                  },
                  onRefresh: () async {
                    _getExamDetails();
                    await _getTrainExamDetails();
                    return true;
                  },
                  child: NestedScrollView(
                    body: buildColumn(),
                    headerSliverBuilder:
                        (BuildContext context, bool innerBoxIsScrolled) {
                      return [
                        SliverToBoxAdapter(
                          child: buildHeaderColumn(),
                        )
                      ];
                    },
                  ),
                ),
                top: 0,
                bottom: 60,
                left: 0,
                right: 0,
              ),
              Positioned(
                child: buildBottomButton(),
                bottom: 20,
                left: 0,
                right: 0,
              )
            ],
          )),
    );
  }

  buildBottomButton() {
    if (_beanTrainExamAppro != null) {
      return Container(
        child: Text("已提交审批"),
      );
    }

    if (_examResultList == null ||
        _beanExam == null ||
        _beanExam.examNumber <= _examResultList.length) {
      return Container();
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        ElevatedButton(
          onPressed: () {
            NavigatorUtils.pushPage(
                context,
                TopicDetilsPage(
                  pageTitle: "培训考试",
                  examUid: _beanExam.examUid,
                  examType: "N",
                  topicEnum: TopicEnum.train,
                  categoryOne:
                      'trainExam_${_beanExam.id}_${widget.approveBean.trainId}',
                  categoryTwo: null,
                ), callback: (value) {
              if (value != null) {
                _problemEndModel = value;
                setState(() {});
              }
            });
          },
          child: Text("练习一下"),
        ),
        SizedBox(
          width: 20,
        ),
        ElevatedButton(
          onPressed: () {
            NavigatorUtils.pushPage(
                context,
                TopicDetilsPage(
                  pageTitle: "培训考试",
                  examType: "Y",
                  examUid: _beanExam.examUid,
                  examBean:
                      BeanExamBean.fromUid(_beanExam.examUid, _beanExam.id),
                  topicEnum: TopicEnum.train,
                  categoryOne:
                      'trainExam_${_beanExam.id}_${widget.approveBean.trainId}',
                  categoryTwo: null,
                ), callback: (value) {
              if (value != null) {
                _problemEndModel = value;
                _getTrainExamDetails();
                setState(() {});
              }
            });
          },
          child: Text("开始考试"),
        ),
      ],
    );
  }

  Widget buildHeaderColumn() {
    if (_beanExam == null) {
      return SizedBox();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          "考试基本信息",
          style: TextStyle(fontWeight: FontWeight.w600, color: Colors.black),
        ),
        SizedBox(
          height: 10,
        ),
        buildItem(
          "assets/images/2.0x/exam_icon_1.png",
          Text(
            "${_beanExam.examTitle}",
            style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
          ),
        ),
        buildItem(
          "assets/images/2.0x/exam_icon_2.png",
          Text(
            "考试时间为 ${_beanExam.examTim} 分钟",
            style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
          ),
        ),
        buildItem(
          "assets/images/2.0x/exam_icon_3.png",
          Text(
            "考试及格分数为总题的 ${_beanExam.examPercent}%,每题1分；考试次数限制为 ${_beanExam.examNumber} 次",
            style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
          ),
        ),
      ],
    );
  }

  ProblemEndModel _problemEndModel;

  Widget buildColumn() {
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_beanExam == null) {
      return NoDataWidget(
        clickCallBack: () {
          _getExamDetails();
        },
      );
    }
    if (_problemEndModel != null) {
      return buildShowExamResultFunction();
    }

    return buildShowExamResultFunction();
  }

  Widget buildItem(String imagePath, Widget text) {
    return Container(
      margin: EdgeInsets.only(bottom: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Image.asset(
            imagePath,
            width: 14,
          ),
          SizedBox(
            width: 8,
          ),
          Expanded(
            child: text,
          ),
        ],
      ),
    );
  }

  BeanExam _beanExam;
  bool _isLoading = true;
  BeanTrainExamAppro _beanTrainExamAppro;

  void _getExamDetails() async {
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.examDetailsByExamId + "/${widget.approveBean.examId}");
    _isLoading = false;
    if (statisRresponseInfo.success) {
      _beanExam = BeanExam.fromMap(statisRresponseInfo.data);
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
    }
    _beanTrainExamAppro =
        await getTrainExamApproDetails(widget.approveBean.trainId);
    if (mounted) {
      setState(() {});
    }
  }

  Widget buildShowExamResultFunction() {
    List<Widget> listWidget = [];
    BeanExamResult max;
    for (int i = 0; i < _examResultList.length; i++) {
      BeanExamResult item = _examResultList[i];
      if (max == null) {
        max = item;
      } else {
        if (item.obtainScore > max.obtainScore) {
          max = item;
        }
      }
    }

    for (int i = 0; i < _examResultList.length; i++) {
      BeanExamResult item = _examResultList[i];
      bool isMax = false;
      if (item.id == max.id) {
        isMax = true;
      }
      listWidget.add(createExamItem(item, isMax));
    }
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            "考试记录",
            style: TextStyle(fontWeight: FontWeight.w600, color: Colors.black),
          ),
          SizedBox(
            height: 14,
          ),
          ...listWidget
        ],
      ),
    );
  }

  Widget createExamItem(BeanExamResult item, bool isMax) {
    int answerTime = 0;
    int score = 0;
    String createTime = '刚刚';
    if (_examResultList != null) {
      answerTime = item.answerTime;
      score = item.obtainScore ~/ 10;
      createTime = item.createTime;
    }
    if (_problemEndModel != null) {
      answerTime = _problemEndModel.answerTime;
      score = _problemEndModel.obtainScore ~/ 10;
    }
    int min = answerTime ~/ 60;
    int second = (answerTime % 60);
    String minStr = min > 9 ? "$min分" : "0$min分";
    String secondStr = second > 9 ? "$second秒" : "0$second秒";

    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        buildItem(
          "assets/images/2.0x/exam_icon_2.png",
          Row(
            children: [
              Expanded(
                child: Text(
                  "考试时间 $createTime",
                  style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
                ),
              ),
              isMax
                  ? Text(
                      "有效",
                      style: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 14,
                          color: Colors.red),
                    )
                  : SizedBox(),
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(left: 22, bottom: 20),
          child: Row(
            children: [
              Text(
                "用时 $minStr $secondStr ",
                style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
              ),
              Expanded(
                child: Text(
                  "得分 $score 分",
                  textAlign: TextAlign.end,
                  style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
                ),
              )
            ],
          ),
        ),
      ],
    );
  }

  //查询考试详情
  Future<bool> _getTrainExamDetails() async {
    LogUtils.e("开始获取考试详情");
    _examResultList = await getTrainExamDetails(
        widget.approveBean.examId, widget.approveBean.trainId);
    if (_examResultList != null) {
      LogUtils.e("f考试详情获取结束 ${_examResultList.length}");
    } else {
      LogUtils.e("f考试详情获取结束 list is null ");
    }
    _isLoading = false;
    if (mounted) {
      setState(() {});
    }
    return true;
  }
}
